import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt

# step1:准备数据集
x_data = torch.Tensor([[1.0],[2.0],[3.0]])  # 3*1的矩阵
y_data = torch.Tensor([[0], [0], [1]])  # 3*1的矩阵 二分类任务 分为0与1


# step2:构建模型
class LogisticRegressionModel(torch.nn.Module):
    def __init__(self):
        super(LogisticRegressionModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    # 重写前向传播
    def forward(self, x):
        y_pred = F.sigmoid(self.linear(x))  # 将线性模型sigmoid化使分布在[0,1]
        return y_pred


model = LogisticRegressionModel()  #创建模型

#step3:准备损失函数与优化器
criterion = torch.nn.BCELoss(size_average=False)#二分类铰链损失函数
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)#准备优化器 随机梯度下降 学习率为0.01

#step4:准备训练
for epoch in range(1000):
    y_pred = model(x_data)
    loss= criterion(y_pred,y_data)
    print(epoch,loss.item())

    optimizer.zero_grad()#优化器梯度清零
    loss.backward()#进行反向传播
    optimizer.step()#迭代优化

#绘图
x = np.linspace(0,10,200)
x_t = torch.Tensor(x).view(((200,1)))
y_t = model(x_t)
y = y_t.data.numpy()
plt.plot(x,y)
plt.plot([0,10],[0.5,0.5],c='r')
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()


